<?php

namespace app\api\model\kuyou\applet;

use app\api\controller\kuyou\applet\Commons;
use think\Model;
use think\Db;
use Exception;
use app\api\model\kuyou\applet\Goods as Goodss;
class Allocation extends Model
{

    // 表名
    protected $name = 'kuyou_allocation';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';

    /**
     * 获取列表
     * @param array $where
     * @param int $page
     * @param int $limit
     * @return array
     */
    public static function getList($where,$page,$limit,$list_type,$sort_field,$sort_type){
        $app_page = config('app_page');
        $app_page = $app_page===false?false:true;
        $pageStatus = true;
        if($app_page){
            if($page<0){
                $pageStatus = false;
            }
        }
        $store = Db::name('kuyou_stores')->column('name','id');

        if($list_type==1){
            if($pageStatus){
                $list = collection(self::where(function ($query) use ($where) {
                    $query->where($where);
                })->order($sort_field,$sort_type)->page($page,$limit)->field("id,purchase_code,FROM_UNIXTIME(purchase_time,'%Y-%m-%d') as purchase_time,
            preparation_id,examine_id,examine_status,print_num,remarks,operation_id")->select())->toArray();
            }else{
                $list = collection(self::where(function ($query) use ($where) {
                    $query->where($where);
                })->order($sort_field,$sort_type)->field("id,purchase_code,FROM_UNIXTIME(purchase_time,'%Y-%m-%d') as purchase_time,
            preparation_id,examine_id,examine_status,print_num,examine_time,remarks,operation_id")->select())->toArray();
            }
            foreach ($list as $list_k=>$list_v){
                $list[$list_k]['preparation_name'] = Db::name('admin')->where(['id'=>$list_v['preparation_id']])->value('username');
                $list[$list_k]['operation_name']   = Db::name('admin')->where(['id'=>$list_v['operation_id']])->value('username');
                $list[$list_k]['examine_name']   = Db::name('admin')->where(['id'=>$list_v['examine_id']])->value('username');

                $info_list = Db::name('kuyou_allocation_info')->alias('ai')
                    ->where(['allocation_id'=>$list_v['id']])
                    ->join('kuyou_goods g','g.id=ai.goods_id')
                    ->join('kuyou_goods_type gt','gt.id=g.goods_type_id')
                    ->join('kuyou_unit u','u.id=ai.goods_unit')
                    ->field('gt.supplier_type_name as type_name,g.goods_name,g.goods_code,g.goods_image,g.batch,g.serial,
                    ai.goods_note,ai.number,u.name as unit_name,ai.remarks as remark,ai.stores_out,ai.stores_enter')
                    ->select();
                foreach ($info_list as $info_list_k=>$info_list_v){
                    $info_list[$info_list_k]['stores_out_name']   = isset($store[$info_list_v['stores_out']])?$store[$info_list_v['stores_out']]:'';;
                    $info_list[$info_list_k]['stores_enter_name']   = isset($store[$info_list_v['stores_enter']])?$store[$info_list_v['stores_enter']]:'';
                }
                $list[$list_k]['info_list'] = $info_list;
            }
            $count = self::where(function ($query) use ($where) {
                $query->where($where);
            })->count();
        }else{
            $sort_field = 'a.'.$sort_field;
            if($pageStatus){
                $list = Db::name('kuyou_allocation_info')->alias('ai')
                    ->join('kuyou_allocation a','a.id=ai.allocation_id')
                    ->where($where)
                    ->join('kuyou_goods g','g.id=ai.goods_id')
                    ->join('kuyou_goods_type gt','gt.id=g.goods_type_id')
                    ->join('kuyou_unit u','u.id=ai.goods_unit')
                    ->page($page,$limit)->order($sort_field,$sort_type)
                    ->field('a.purchase_code,FROM_UNIXTIME(a.purchase_time,\'%Y-%m-%d\') as purchase_time,a.preparation_id,a.examine_id,a.operation_id,a.examine_status,a.remarks,a.print_num,
                gt.supplier_type_name as type_name,g.goods_name,ai.goods_note,ai.number,u.name as unit_name,ai.remarks as remark,ai.stores_out,ai.stores_enter')
                    ->select();
            }else{
                $list = Db::name('kuyou_allocation_info')->alias('ai')
                    ->join('kuyou_allocation a','a.id=ai.allocation_id')
                    ->where($where)
                    ->join('kuyou_goods g','g.id=ai.goods_id')
                    ->join('kuyou_goods_type gt','gt.id=g.goods_type_id')
                    ->join('kuyou_unit u','u.id=ai.goods_unit')
                    ->order($sort_field,$sort_type)
                    ->field('a.id,a.purchase_code,FROM_UNIXTIME(a.purchase_time,\'%Y-%m-%d\') as purchase_time,a.preparation_id,a.examine_id,a.operation_id,a.examine_status,a.remarks,a.print_num,
                gt.supplier_type_name as type_name,g.goods_name,ai.goods_note,ai.number,u.name as unit_name,ai.remarks as remark,ai.stores_out,ai.stores_enter')
                    ->select();
            }
            foreach ($list as $list_k=>$list_v){
                $list[$list_k]['preparation_name'] = Db::name('admin')->where(['id'=>$list_v['preparation_id']])->value('username');
                $list[$list_k]['operation_name']   = Db::name('admin')->where(['id'=>$list_v['operation_id']])->value('username');
                $list[$list_k]['examine_name']   = Db::name('admin')->where(['id'=>$list_v['examine_id']])->value('username');
                $list[$list_k]['stores_out_name']   = isset($store[$list_v['stores_out']])?$store[$list_v['stores_out']]:'';;
                $list[$list_k]['stores_enter_name']   = isset($store[$list_v['stores_enter']])?$store[$list_v['stores_enter']]:'';
            }

            $count = Db::name('kuyou_allocation_info')->alias('ai')
                ->join('kuyou_allocation a','a.id=ai.allocation_id')
                ->where($where)
                ->join('kuyou_goods g','g.id=ai.goods_id')
                ->join('kuyou_goods_type gt','gt.id=g.goods_type_id')
                ->join('kuyou_unit u','u.id=ai.goods_unit')->count();
        }
        return ['list'=>$list,'count'=>$count];
    }

    /**
     * 获取详情
     * @param string $purchase_code
     * @return array
     */
    public static function getDetail($purchase_code){
        $detail = self::where(function ($query) use ($purchase_code) {
            $query->where('purchase_code', '=', $purchase_code);
        })->field("id,purchase_code,preparation_id,examine_id,operation_id,examine_status,examine_time,remarks,print_num,FROM_UNIXTIME(purchase_time,'%Y-%m-%d') as purchase_time")->find();
        if($detail){
            $store = Db::name('kuyou_stores')->column('name','id');
            $info_list = Db::name('kuyou_allocation_info')
                ->where(['allocation_id'=>$detail['id']])
                ->field('goods_id,goods_attr,goods_unit,stores_out,stores_enter,number,goods_batch_id,goods_batch_name,goods_serial_id,remarks,allow_stock,goods_note')->select();
            foreach ($info_list as $info_list_k=>$info_list_v){
                if(!empty($info_list_v['goods_serial_id'])){
                    $info_list[$info_list_k]['goods_serial_id'] = unserialize($info_list_v['goods_serial_id']);
                }else{
                    $info_list[$info_list_k]['goods_serial_id'] = [];
                }
                $info_list[$info_list_k]['goods_batch'] = Db::name('kuyou_goods_batch')->where(['id'=>$info_list_v['goods_batch_id']])
                    ->field("id,batch_name,FROM_UNIXTIME(manufacture,'%Y-%m-%d') as manufacture,guarantee,FROM_UNIXTIME(validity,'%Y-%m-%d') as validity")->find();

                $info_list[$info_list_k]['stores_out_name']   = isset($store[$info_list_v['stores_out']])?$store[$info_list_v['stores_out']]:'';;
                $info_list[$info_list_k]['stores_enter_name']   = isset($store[$info_list_v['stores_enter']])?$store[$info_list_v['stores_enter']]:'';

                $info_list[$info_list_k]['unit_name'] = Db::name('kuyou_unit')->where(['id'=>$info_list_v['goods_unit']])->field('name')->find();
                $info_list[$info_list_k]['goods'] = Db::name('kuyou_goods')->where(['id'=>$info_list_v['goods_id']])->field('goods_code,goods_name,goods_image,batch,serial,more_unit')->find();

                $attribute_id = Db::name('kuyou_goods_attr')->where(['id'=>$info_list_v['goods_attr']])->value('attribute_id');
                $attribute_ids = Db::name('kuyou_aux_combination')->where(['id'=>$attribute_id])->value('attr_ids');
                $attribute_name = '';
                if($attribute_ids){
                    $attribute_ids = explode('&',$attribute_ids);
                    $attribute = Db::name('kuyou_auxiliary')->where(['id'=>['in',$attribute_ids]])->column('name');
                    $attribute_name = implode('/',$attribute);
                }
                $info_list[$info_list_k]['attr_name'] = $attribute_name;
            }
            $detail['info_list'] = $info_list;
        }else{
            return ['status'=>500,'msg'=>'未查询到相关数据'];
        }
        return ['status'=>200,'msg'=>$detail];
    }

    /**
     * 添加
     * @param array $detail
     * @return array
     */
    public static function addDetail($detail){
        if(empty($detail)){
            return ['status'=>400,'msg'=>'参数错误'];
        }else{
            $check = (new Commons())->checkParameter($detail,[
                'purchase_code|单据编号'=>'require',
                'purchase_time|单据时间'=>'require',
                'info_list|详细信息'=>'require',
            ]);
            if(isset($check['status'])){
                return $check;
            }else{
                $status = (new Commons())->checkCode($detail['purchase_code'],13);//验证编号是否合法
                if($status){
                    $examine= (new Commons())->getSet('examine','is_checked');

                    $adminId = (new Commons())->getAdminId();
                    if(empty($adminId)){
                        return ['status'=>410,'msg'=>'登陆无效，请重新登陆'];
                    }

                    $info_list = (array)json_decode($detail['info_list'], true);
                    $set= Db::name('kuyou_sets')->where(['name'=>'serial'])->value('is_checked');
                    $batch= Db::name('kuyou_sets')->where(['name'=>'batch'])->value('is_checked');
                    $data = [];
                    $goods_serial_all = [];
                    foreach ($info_list as $k=>$v){
                        if(!empty($v['goods_id'])){//有产品
                            if(!isset($v['stores_out']) || empty($v['stores_out'])){
                                return ['status'=>500,'msg'=>'请选择调出仓库'];
                            }else if(!isset($v['stores_enter']) || empty($v['stores_enter'])){
                                return ['status'=>500,'msg'=>'请选择调入仓库'];
                            }else if($v['stores_out']==$v['stores_enter']){
                                return ['status'=>500,'msg'=>'调出仓库不能和调入仓库相同'];
                            }

                            $goods = Db::name('kuyou_goods')->where(['id'=>$v['goods_id']])->field('id,serial,batch')->find();

                            if($goods['batch']==1 && $batch==1){
                                if(empty($v['goods_batch_id'])){
                                    return ['status'=>500,'msg'=>'请选择生产批次'];
                                }
                                $batch_data = Db::name('kuyou_goods_batch')->where(['id'=>$v['goods_batch_id']])->find();
                                if(empty($batch_data)){
                                    return ['status'=>500,'msg'=>'生产批次不存在'];
                                }
                            }

                            $serial_code = [];
                            if($goods['serial']==1 && $set==1){
                                if(empty($v['serial'])){
                                    return ['status'=>500,'msg'=>'请输入商品序列号'];
                                }
                                $period_period = $v['serial'];
                                foreach ($period_period as $period_period_k=>$period_period_v){
                                    if(in_array($period_period_v['serial'],$goods_serial_all)){
                                        return ['status'=>500,'msg'=>'商品序列号'.$period_period_v['serial'].'重复'];
                                    }else{
                                        $goods_serial_all[] = $period_period_v['serial'];
                                    }
                                    $serial_code[] = $period_period_v;
                                }
                            }
                            $data[] = [
                                'goods_id'          =>  $goods['id'],//商品信息
                                'goods_attr'        =>  (float)$v['goods_attr'],//商品属性
                                'goods_unit'        =>  (float)$v['goods_unit'],//商品单位
                                'stores_out'        =>  (float)$v['stores_out'],//调出仓库
                                'stores_enter'      =>  (float)$v['stores_enter'],//调入仓库
                                'number'            =>  (float)$v['number'],//数量
                                'allow_stock'       =>  (float)$v['allow_stock'],
                                'goods_batch_id'    =>  (float)$v['goods_batch_id'],
                                'goods_batch_name'  =>  $v['goods_batch_name'],
                                'goods_serial_id'   =>  !empty($serial_code)?serialize($serial_code):null,
                                'remarks'           =>  $v['remarks'],
                                'goods_note'        =>  $v['goods_note'],
                            ];
                        }
                    }
                    if(!empty($data)){
                        $rowdata = [
                            'purchase_code'     =>  $detail['purchase_code'],
                            'purchase_time'     =>  strtotime($detail['purchase_time']),
                            'remarks'           =>  $detail['remarks'],//备注
                            'preparation_id'    =>  $adminId,
                            'operation_id'      =>  $adminId,
                            'createtime'        => time(),
                            'updatetime'        => time(),
                        ];
                    }

                    $model = new Allocation();
                    $row = $model->where(['purchase_code'=>$detail['purchase_code']])->value('id');
                    if($row){
                        return ['status'=>500,'msg'=>'编号已存在'];
                    }
                    $result = false;
                    Db::startTrans();
                    try {
                        $model->allowField(true)->save($rowdata);
                        $result = $model->id;
                        if($result){
                            foreach ($data as $data_k=>$data_v){
                                $data_v['allocation_id'] = $result;
                                $data[$data_k] = $data_v;
                            }
                            Db::name('kuyou_allocation_info')->insertAll($data);
                        }
                        Db::commit();
                    } catch (Exception $e) {
                        Db::rollback();
                        return ['status'=>500,'msg'=>$e->getMessage()];
                    }
                    if($result){
                        if($examine!=1){
                            try {
                                $exa = self::examine($detail['purchase_code']);
                            } catch (Exception $e) {
                            }
                            if(!isset($exa['status']) || (isset($exa['status']) && $exa['status']!=1)){
                                try {
                                    self::delDetail($detail['purchase_code']);
                                } catch (Exception $e) {
                                }
                                return ['status'=>500,'msg'=>$exa['msg']];
                            }
                        }
                        return ['status'=>200,'msg'=>$detail['purchase_code']];
                    }else{
                        return ['status'=>500,'msg'=>'添加失败'];
                    }
                }else{
                    return ['status'=>500,'msg'=>'编号规则错误'];
                }
            }
        }
    }

    /**
     * 更新
     * @param array $detail
     * @return array
     */
    public static function editDetail($detail){
        if(empty($detail)){
            return ['status'=>400,'msg'=>'参数错误'];
        }else{
            $check = (new Commons())->checkParameter($detail,[
                'old_purchase_code|原单据编号'=>'require',
                'purchase_code|单据编号'=>'require',
                'purchase_time|单据时间'=>'require',
                'info_list|详细信息'=>'require',
            ]);
            if(isset($check['status'])){
                return $check;
            }else{
                $adminId = (new Commons())->getAdminId();
                if(empty($adminId)){
                    return ['status'=>410,'msg'=>'登陆无效，请重新登陆'];
                }
                $status = (new Commons())->checkCode($detail['purchase_code'],13);//验证编号是否合法
                if($status){
                    $model = new Allocation();
                    $row = $model->where(['purchase_code'=>$detail['old_purchase_code']])->find();
                    if(empty($row)){
                        return ['status'=>500,'msg'=>'修改的单据不存在'];
                    }

                    $info_id = Db::name('kuyou_allocation_info')->where(['allocation_id'=>$row['id']])->column('id');

                    $examine= (new Commons())->getSet('examine','is_checked');

                    $info_list = (array)json_decode($detail['info_list'], true);
                    $set= Db::name('kuyou_sets')->where(['name'=>'serial'])->value('is_checked');
                    $batch= Db::name('kuyou_sets')->where(['name'=>'batch'])->value('is_checked');
                    $data = [];
                    $goods_serial_all = [];
                    foreach ($info_list as $k=>$v){
                        if(!empty($v['goods_id'])){//有产品
                            if(!isset($v['stores_out']) || empty($v['stores_out'])){
                                return ['status'=>500,'msg'=>'请选择调出仓库'];
                            }else if(!isset($v['stores_enter']) || empty($v['stores_enter'])){
                                return ['status'=>500,'msg'=>'请选择调入仓库'];
                            }else if($v['stores_out']==$v['stores_enter']){
                                return ['status'=>500,'msg'=>'调出仓库不能和调入仓库相同'];
                            }

                            $goods = Db::name('kuyou_goods')->where(['id'=>$v['goods_id']])->field('id,serial,batch')->find();

                            if($goods['batch']==1 && $batch==1){
                                if(empty($v['goods_batch_id'])){
                                    return ['status'=>500,'msg'=>'请选择生产批次'];
                                }
                                $batch_data = Db::name('kuyou_goods_batch')->where(['id'=>$v['goods_batch_id']])->find();
                                if(empty($batch_data)){
                                    return ['status'=>500,'msg'=>'生产批次不存在'];
                                }
                            }

                            $serial_code = [];
                            if($goods['serial']==1 && $set==1){
                                if(empty($v['serial'])){
                                    return ['status'=>500,'msg'=>'请输入商品序列号'];
                                }
                                $period_period = $v['serial'];
                                foreach ($period_period as $period_period_k=>$period_period_v){
                                    if(in_array($period_period_v['serial'],$goods_serial_all)){
                                        return ['status'=>500,'msg'=>'商品序列号'.$period_period_v['serial'].'重复'];
                                    }else{
                                        $goods_serial_all[] = $period_period_v['serial'];
                                    }
                                    $serial_code[] = $period_period_v;
                                }
                            }
                            $data[] = [
                                'goods_id'          =>  $goods['id'],//商品信息
                                'goods_attr'        =>  (float)$v['goods_attr'],//商品属性
                                'goods_unit'        =>  (float)$v['goods_unit'],//商品单位
                                'stores_out'        =>  (float)$v['stores_out'],//调出仓库
                                'stores_enter'      =>  (float)$v['stores_enter'],//调入仓库
                                'number'            =>  (float)$v['number'],//数量
                                'allow_stock'       =>  (float)$v['allow_stock'],
                                'goods_batch_id'    =>  (float)$v['goods_batch_id'],
                                'goods_batch_name'  =>  $v['goods_batch_name'],
                                'goods_serial_id'   =>  !empty($serial_code)?serialize($serial_code):null,
                                'remarks'           =>  $v['remarks'],
                                'goods_note'        =>  $v['goods_note'],
                            ];
                        }
                    }
                    if(!empty($data)){
                        $rowdata = [
                            'purchase_code'     =>  $detail['purchase_code'],
                            'purchase_time'     =>  strtotime($detail['purchase_time']),
                            'remarks'           =>  $detail['remarks'],//备注
                            'preparation_id'    =>  $adminId,
                            'operation_id'      =>  $adminId,
                        ];
                    }

                    if($detail['purchase_code']!=$detail['old_purchase_code']){
                        $purchase_id = $model->where(['purchase_code'=>$detail['purchase_code']])->value('id');
                        if($purchase_id){
                            return ['status'=>500,'msg'=>'单据编号已使用，请重新输入单据编号'];
                        }
                    }

                    if($row){
                        $res = false;
                        //关闭审核功能需先反审核一次已审核数据
                        if($examine!=1 && $row['examine_status']==1){
                            self::examinef($detail['old_purchase_code']);
                        }
                        Db::startTrans();
                        try {
                            $rowdata['updatetime'] = time();
                            $res = $model->where(['purchase_code'=>$detail['old_purchase_code']])->update($rowdata);
                            Db::name('kuyou_allocation_info')->where(['id'=>['in',$info_id]])->delete();

                            foreach ($data as $data_k=>$data_v){
                                $data_v['allocation_id'] = $row['id'];
                                $data[$data_k] = $data_v;
                            }
                            Db::name('kuyou_allocation_info')->insertAll($data);

                            Db::commit();
                        } catch (Exception $e) {
                            Db::rollback();
                            return ['status'=>500,'msg'=>$e->getMessage()];
                        }
                        if($res){
                            if($examine!=1){
                                try {
                                    $exa = self::examine($detail['purchase_code']);
                                } catch (Exception $e) {
                                }
                                if(!isset($exa['status']) || (isset($exa['status']) && $exa['status']!=1)){
                                    return ['status'=>500,'msg'=>$exa['msg']];
                                }
                            }
                            return ['status'=>200,'msg'=>'更新成功'];
                        }else{
                            return ['status'=>500,'msg'=>'更新失败'];
                        }
                    }else{
                        return ['status'=>500,'msg'=>'未查询到可更新数据'];
                    }
                }else{
                    return ['status'=>500,'msg'=>'编号规则错误'];
                }
            }
        }
    }

    /**
     * 删除
     * @param string $purchase_code
     * @return array
     */
    public static function delDetail($purchase_code){
        if(empty($purchase_code)){
            return ['status'=>400,'msg'=>'参数错误'];
        }else{
            $purchase_code = explode(',',$purchase_code);
            $model = new Allocation();
            $examine= (new Commons())->getSet('examine','is_checked');

            $list = $model->where(['purchase_code'=>['in',$purchase_code]])->select();
            foreach ($list as $list_k=>$list_v){
                if($list_v['examine_status']==1 && $examine==1){
                    return ['status'=>500,'msg'=>'不能删除已审核的数据'];
                }
            }

            $count = 0;
            $res = false;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    if ($v['examine_status']==1 && $examine!=1){
                        try {
                            self::examinef($v['purchase_code']);
                        } catch (Exception $e) {
                        }
                    }
                    $res = $model->where(['purchase_code'=>$v['purchase_code']])->delete();
                    $count += $res;
                    Db::name('kuyou_allocation_info')->where(['allocation_id'=>$v['id']])->delete();
                }
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                return ['status'=>500,'msg'=>$e->getMessage()];
            }
            if($res){
                return ['status'=>200,'msg'=>$count];
            }else{
                return ['status'=>500,'msg'=>'删除失败'];
            }
        }
    }

    /**
     * 审核
     * @param array $purchase_code
     * @return array
     */
    public static function examine($purchase_code = null){
        if(empty($purchase_code)){
            return ['status'=>400,'msg'=>'请选择要操作的数据'];
        }
        $adminId = (new Commons())->getAdminId();
        if(empty($adminId)){
            return ['status'=>410,'msg'=>'登陆无效，请重新登陆'];
        }
        $model = new Allocation();
        $list = $model->where(['purchase_code'=>['in',$purchase_code],'examine_status'=>'0'])->select();
        if(empty($list)){
            return ['status'=>500,'msg'=>'请选择需要审核的数据'];
        }
        $ids = $model->where(['purchase_code'=>['in',$purchase_code],'examine_status'=>'0'])->column('id');

        $number_decimal = Db::name('kuyou_sets')->where(['name'=>'number_decimal'])->value('value');
        $serial= Db::name('kuyou_sets')->where(['name'=>'serial'])->value('is_checked');//序列号设置
        $batch= Db::name('kuyou_sets')->where(['name'=>'batch'])->value('is_checked');//批次设置

        $info_list = Db::name('kuyou_allocation_info')->where(['allocation_id'=>['in',$ids]])->select();

        $goods_stock_add = [];$goods_stock_edit = [];
        $goods_batch_add = [];$goods_batch_edit = [];
        $serial_edit = [];$goods_batch_log = [];
        $goods_stock_log = [];
        foreach ($info_list as $list_k=>$list_v){

            $goods = Db::name('kuyou_goods')->where(['id'=>$list_v['goods_id']])->field('id,goods_code,goods_name,attribute_id,auxiliary,serial,inventory,unit_id,batch')->find();
            //先通过单位计算需修改多单位商品的库存数量
            if($goods['unit_id']==$list_v['goods_unit']){
                $stock_number = $list_v['number'];
            }else{
                $unit_conversion = Db::name('kuyou_unit_conversion')->where(['main_unit'=>$goods['unit_id'],'vice_unit'=>$list_v['goods_unit']])->value('advance_rate');
                if(empty($unit_conversion)){
                    return ['status'=>500,'msg'=>'商品单位信息查询失败'];
                }else{
                    $stock_number = round(($list_v['number']*$unit_conversion),$number_decimal);
                }
            }
            if($goods['auxiliary']==1 && empty($list_v['goods_attr'])){
                return ['status'=>500,'msg'=>'请选择商品属性'];
            }
            if(!empty($list_v['goods_attr'])){
                $attr_id = Db::name('kuyou_goods_attr')->where(['id'=>$list_v['goods_attr']])->value('attribute_id');
            }
            //查询调出仓库库存
            $where = [];
            $where['goods_id'] = $goods['id'];
            if(isset($attr_id)){
                $where['attribute_id'] = $attr_id;
            }
            $where['stores_id'] = $list_v['stores_out'];
            $goods_stock = Db::name('kuyou_goods_stock')->where($where)->find();
            //减调出仓库库存
            if(empty($goods_stock)){
                return ['status'=>500,'msg'=>'商品'.$goods['goods_name'].'库存不足'];
            }else if($goods_stock['stock']<$stock_number){
                return ['status'=>500,'msg'=>'商品'.$goods['goods_name'].'库存不足'];
            }else{
                if(isset($goods_stock_edit[$goods_stock['id']])){
                    $goods_stock_edit[$goods_stock['id']] -= $stock_number;
                }else{
                    $goods_stock_edit[$goods_stock['id']] = $goods_stock['stock']-$stock_number;
                }
            }
            //收发详情
            $allocation = Db::name('kuyou_allocation')->where(['id'=>$list_v['allocation_id']])->field('purchase_code,purchase_time,remarks')->find();
            //获取成本单价
            $balance_cost=0;$balance_unit=0;
            $goods['id'] = $list_v['goods_id'];
            $goods['store'] = $list_v['stores_out'];
            $goods['attr_id'] = $list_v['goods_attr'];
            $goodsInfo = Goodss::getGoodsInfo($goods);
            if(!isset($goodsInfo['msg']['price_data'][0]['purchase'])){
                return ['status'=>500,'msg'=>'商品信息获取错误'];
            }else{
                $balance_unit = $goodsInfo['msg']['price_data'][0]['purchase'];
            }
            //获取成本单价结束

            if($goods){
                //调出
                $goods_stock_log[] = [
                    'purchase_code' => $allocation['purchase_code'],
                    'purchase_id'   => $list_v['id'],
                    'purchase_time' => $allocation['purchase_time'],
                    'business_type' => '6',
                    'goods_id'      => $goods['id'],
                    'goods_code'    => $goods['goods_code'],
                    'attribute_id'  => (float)$list_v['goods_attr'],
                    'goods_unit'    => (float)$list_v['goods_unit'],
                    'stores_id'     => (float)$list_v['stores_out'],
                    'remark'        => $list_v['remarks'],
                    'enter_number'  => null,
                    'enter_basics'  => null,
                    'enter_unit'    => null,
                    'enter_cost'    => null,
                    'out_number'    => (float)$list_v['number'],
                    'out_basics'    => (float)$stock_number,
                    'out_unit'      => $balance_unit,
                    'out_cost'      => round($balance_unit*$stock_number,4),
                    'createtime'    => time(),
                    'updatetime'    => time(),
                ];
                //调入
                $goods_stock_log[] = [
                    'purchase_code' => $allocation['purchase_code'],
                    'purchase_id'   => $list_v['id'],
                    'purchase_time' => $allocation['purchase_time'],
                    'business_type' => '6',
                    'goods_id'      => $goods['id'],
                    'goods_code'    => $goods['goods_code'],
                    'attribute_id'  => (float)$list_v['goods_attr'],
                    'goods_unit'    => (float)$list_v['goods_unit'],
                    'stores_id'     => (float)$list_v['stores_enter'],
                    'remark'        => $list_v['remarks'],
                    'enter_number'  => (float)$list_v['number'],
                    'enter_basics'  => (float)$stock_number,
                    'enter_unit'    => $balance_unit,
                    'enter_cost'    => round($balance_unit*$stock_number,4),
                    'out_number'    => null,
                    'out_basics'    => null,
                    'out_unit'      => null,
                    'out_cost'      => null,
                    'createtime'    => time(),
                    'updatetime'    => time(),
                ];
            }
            //收发详情结束
            //调入仓库
            $where = [];
            $where['goods_id'] = $goods['id'];
            if(isset($attr_id)){
                $where['attribute_id'] = $attr_id;
            }
            $where['stores_id'] = $list_v['stores_enter'];
            $goods_stock = Db::name('kuyou_goods_stock')->where($where)->find();
            if(empty($goods_stock)){//调入仓库无数据，新增仓储数据
                $where['stores_id'] = $list_v['stores_out'];
                $goods_stocks = Db::name('kuyou_goods_stock')->where($where)->find();
                if(isset($goods_stock_add[$goods_stocks['id']])){
                    $goods_stock_add[$goods_stocks['id']]['stock'] += $stock_number;
                }else{
                    unset($goods_stocks['id']);
                    $goods_stocks['stock'] = $stock_number;
                    $goods_stocks['stores_id'] = $list_v['stores_enter'];
                    $goods_stocks['createtime'] = time();
                    $goods_stocks['updatetime'] = time();
                    $goods_stock_add[$goods_stock['id']] = $goods_stocks;
                }
            }else{
                if(isset($goods_stock_edit[$goods_stock['id']])){
                    $goods_stock_edit[$goods_stock['id']] += $stock_number;
                }else{
                    $goods_stock_edit[$goods_stock['id']] = $goods_stock['stock']+$stock_number;
                }
            }
            foreach ($goods_stock_edit as $k=>$v){
                if($v<0){
                    return ['status'=>500,'msg'=>'商品'.$goods['goods_name'].'库存不足'];
                }
            }

            if($goods['batch']==1 && $batch==1){//启用批次管理

                //调出商品批次跟踪
                $allocation = Db::name('kuyou_allocation')->where(['id'=>$list_v['allocation_id']])->field('purchase_code,purchase_time,remarks')->find();
                $goods_batch_log[] = [
                    'goods_id'      => $goods['id'],
                    'goods_unit'    => $list_v['goods_unit'],
                    'stores_id'     => $list_v['stores_out'],
                    'batch_id'      => (float)$list_v['goods_batch_id'],
                    'number'        => (float)$list_v['number'],
                    'purchase_code' => $allocation['purchase_code'],
                    'purchase_time' => $allocation['purchase_time'],
                    'business_type' => '6',
                    'remarks'       => $allocation['remarks'],
                    'order_id'      => $list_v['id'],
                    'createtime'    => time(),
                    'updatetime'    => time(),
                ];
                //调出商品批次跟踪结束
                //调入商品批次跟踪
                $goods_batch_log[] = [
                    'goods_id'      => $goods['id'],
                    'goods_unit'    => $list_v['goods_unit'],
                    'stores_id'     => $list_v['stores_enter'],
                    'batch_id'      => (float)$list_v['goods_batch_id'],
                    'number'        => (float)$list_v['number'],
                    'purchase_code' => $allocation['purchase_code'],
                    'purchase_time' => $allocation['purchase_time'],
                    'business_type' => '6',
                    'remarks'       => $allocation['remarks'],
                    'order_id'      => $list_v['id'],
                    'createtime'    => time(),
                    'updatetime'    => time(),
                ];
                //调入商品批次跟踪结束

                $where = [];
                $where['goods_id'] = $goods['id'];
                if(!empty($list_v['goods_attr'])){
                    $where['attribute_id'] = $list_v['goods_attr'];
                }
                $where['stores_id'] = $list_v['stores_out'];
                $where['batch_id'] = $list_v['goods_batch_id'];
                $goods_batch_stock = Db::name('kuyou_goods_batch_stock')->where($where)->find();
                if(empty($goods_batch_stock)){
                    return ['status'=>500,'msg'=>'商品'.$goods['goods_name'].'批次信息查询失败'];
                }else if($goods_batch_stock['stock']<$stock_number){
                    return ['status'=>500,'msg'=>'商品'.$goods['goods_name'].'批次'.$list_v['goods_batch_name'].'库存不足'];
                }else{
                    if(isset($goods_batch_edit[$goods_batch_stock['id']])){
                        $goods_batch_edit[$goods_batch_stock['id']] -= $stock_number;
                    }else{
                        $goods_batch_edit[$goods_batch_stock['id']] = $goods_batch_stock['stock']-$stock_number;
                    }
                }
                foreach ($goods_batch_edit as $k=>$v){
                    if($v<0){
                        return ['status'=>500,'msg'=>'商品'.$goods['goods_name'].'批次'.$list_v['goods_batch_name'].'库存不足'];
                    }
                }

                $where['stores_id'] = $list_v['stores_enter'];
                $goods_batch_stock = Db::name('kuyou_goods_batch_stock')->where($where)->find();
                if(empty($goods_batch_stock)){//调入批次仓库无数据，新增仓储数据
                    $where['stores_id'] = $list_v['stores_out'];
                    $goods_stocks = Db::name('kuyou_goods_batch_stock')->where($where)->find();
                    if(isset($goods_batch_add[$goods_stocks['id']])){
                        $goods_batch_add[$goods_stocks['id']]['stock'] += $stock_number;
                    }else{
                        unset($goods_stocks['id']);
                        $goods_stocks['stock'] = $stock_number;
                        $goods_stocks['stores_id'] = $list_v['stores_enter'];
                        $goods_stocks['createtime'] = time();
                        $goods_stocks['updatetime'] = time();
                        $goods_batch_add[$goods_stock['id']] = $goods_stocks;
                    }
                }else{
                    if(isset($goods_batch_edit[$goods_batch_stock['id']])){
                        $goods_batch_edit[$goods_batch_stock['id']] += $stock_number;
                    }else{
                        $goods_batch_edit[$goods_batch_stock['id']] = $goods_batch_stock['stock']+$stock_number;
                    }
                }
            }
            if($goods['serial']==1 && $serial==1){//启用序列号管理
                if(empty($list_v['goods_serial_id'])){
                    return ['status'=>500,'msg'=>'请选择序列号'];
                }
                $goods_serial = unserialize($list_v['goods_serial_id']);
                $serial_number = [];
                foreach ($goods_serial as $goods_serial_k=>$goods_serial_v){
                    $serial_number[] = $goods_serial_v['serial'];
                }
                $where = [];
                $where['goods_id'] = $goods['id'];
                $where['attribute_id'] = $list_v['goods_attr'];
                $where['stores_id'] = $list_v['stores_out'];
                $where['serial'] = ['in',$serial_number];
                $where['store_status'] = '1';
                $goods_number_stock = Db::name('kuyou_goods_serial')->where($where)->column('id');//需修改仓库的序列号ID
                if(sizeof($goods_number_stock)!=sizeof($serial_number)){
                    return ['status'=>500,'msg'=>'商品'.$goods['goods_name'].'序列号存在未在库，请重新选择'];
                }
                foreach ($goods_number_stock as $k=>$v){
                    if(!isset($serial_edit[$v])){
                        $serial_edit[$v] = ['id'=>$v,'stores_id'=>$list_v['stores_enter']];
                    }
                }
            }
        }

        Db::startTrans();
        try {
            if(!empty($goods_stock_log)){
                Db::name('kuyou_goods_log')->insertAll($goods_stock_log);
            }
            if(!empty($goods_batch_log)){
                Db::name('kuyou_goods_batch_log')->insertAll($goods_batch_log);
            }

            $result = $model->where(['id'=>['in',$ids],'examine_status'=>'0'])
                ->update(['examine_status'=>1,'examine_id'=>$adminId,'examine_time'=>time(),'operation_id'=>$adminId]);
            if(!empty($goods_stock_add)){
                Db::name('kuyou_goods_stock')->insertAll($goods_stock_add);
            }
            if(!empty($goods_stock_edit)){
                foreach ($goods_stock_edit as $k=>$v){
                    Db::name('kuyou_goods_stock')->where(['id'=>$k])->update(['stock'=>$v]);
                }
            }
            if(!empty($goods_batch_add)){
                foreach ($goods_batch_add as $goods_batch_add_k=>$goods_batch_add_v){
                    $where = [];
                    $where['goods_code'] = $goods_batch_add_v['goods_code'];
                    $where['stores_id'] = $goods_batch_add_v['stores_id'];
                    $where['batch_id'] = $goods_batch_add_v['batch_id'];
                    if($goods_batch_add_v['attribute_id']>0){
                        $where['attribute_id'] = $goods_batch_add_v['attribute_id'];
                    }
                    $stock = Db::name('kuyou_goods_batch_stock')->where($where)->find();
                    if($stock){
                        Db::name('kuyou_goods_batch_stock')->where(['id'=>$stock['id']])->inc('stock',$goods_batch_add_v['stock'])->update();
                    }else{
                        Db::name('kuyou_goods_batch_stock')->insert($goods_batch_add_v);
                    }
                }
            }
            if(!empty($goods_batch_edit)){
                foreach ($goods_batch_edit as $k=>$v){
                    Db::name('kuyou_goods_batch_stock')->where(['id'=>$k])->update(['stock'=>$v]);
                }
            }
            if(!empty($serial_edit)){
                (new GoodsSerial())->saveAll($serial_edit);
            }
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            return ['status'=>500,'msg'=>$e->getMessage()];
        }
        if(isset($result) && $result !== false){
            return ['status'=>1,'msg'=>sizeof($list)];
        }else{
            return ['status'=>500,'msg'=>'审核失败'];
        }
    }

    /**
     * 反审核
     * @param array $purchase_code
     * @return array
     */
    public static function examinef($purchase_code = null){
        if(empty($purchase_code)){
            return ['status'=>400,'msg'=>'请选择要操作的数据'];
        }
        $adminId = (new Commons())->getAdminId();
        if(empty($adminId)){
            return ['status'=>410,'msg'=>'登陆无效，请重新登陆'];
        }
        $number_decimal = Db::name('kuyou_sets')->where(['name'=>'number_decimal'])->value('value');
        $serial= Db::name('kuyou_sets')->where(['name'=>'serial'])->value('is_checked');//序列号设置
        $batch= Db::name('kuyou_sets')->where(['name'=>'batch'])->value('is_checked');//批次设置

        $model = new Allocation();
        $list = $model->where(['purchase_code'=>['in',$purchase_code],'examine_status'=>'1'])->field('id,purchase_code')->select();
        if(empty($list)){
            return ['status'=>500,'msg'=>'请选择需要反审核的数据'];
        }
        $ids = $model->where(['purchase_code'=>['in',$purchase_code],'examine_status'=>'1'])->column('id');
        $info_list = Db::name('kuyou_allocation_info')->where(['allocation_id'=>['in',$ids]])->select();

        $goods_stock_add = [];$goods_stock_edit = [];
        $goods_batch_add = [];$goods_batch_edit = [];
        $serial_edit = [];$info_ids = [];
        foreach ($info_list as $list_k=>$list_v){
            $info_ids[] = $list_v['id'];
            $goods = Db::name('kuyou_goods')->where(['id'=>$list_v['goods_id']])->field('auxiliary,serial,id,goods_name,attribute_id,inventory,unit_id,batch')->find();
            //先通过单位计算需修改多单位商品的库存数量
            if($goods['unit_id']==$list_v['goods_unit']){
                $stock_number = $list_v['number'];
            }else{
                $unit_conversion = Db::name('kuyou_unit_conversion')->where(['main_unit'=>$goods['unit_id'],'vice_unit'=>$list_v['goods_unit']])->value('advance_rate');
                if(empty($unit_conversion)){
                    return ['status'=>500,'msg'=>'商品单位信息查询失败'];
                }else{
                    $stock_number = round(($list_v['number']*$unit_conversion),$number_decimal);
                }
            }
            if($goods['auxiliary']==1 && empty($list_v['goods_attr'])){
                return ['status'=>500,'msg'=>'请选择商品属性'];
            }
            if(!empty($list_v['goods_attr'])){
                $attr_id = Db::name('kuyou_goods_attr')->where(['id'=>$list_v['goods_attr']])->value('attribute_id');
            }
            //查询调入仓库库存
            $where = [];
            $where['goods_id'] = $goods['id'];
            if(isset($attr_id)){
                $where['attribute_id'] = $attr_id;
            }
            $where['stores_id'] = $list_v['stores_enter'];
            $goods_stock = Db::name('kuyou_goods_stock')->where($where)->find();
            //减调入仓库库存
            if(empty($goods_stock)){
                return ['status'=>500,'msg'=>'商品'.$goods['goods_name'].'库存不足'];
            }else if($goods_stock['stock']<$stock_number){
                return ['status'=>500,'msg'=>'商品'.$goods['goods_name'].'库存不足'];
            }else{
                if(isset($goods_stock_edit[$goods_stock['id']])){
                    $goods_stock_edit[$goods_stock['id']] -= $stock_number;
                }else{
                    $goods_stock_edit[$goods_stock['id']] = $goods_stock['stock']-$stock_number;
                }
            }
            //调出仓库
            $where = [];
            $where['goods_id'] = $goods['id'];
            if(isset($attr_id)){
                $where['attribute_id'] = $attr_id;
            }
            $where['stores_id'] = $list_v['stores_out'];
            $goods_stock = Db::name('kuyou_goods_stock')->where($where)->find();
            if(empty($goods_stock)){//调出仓库无数据，新增仓储数据
                $where['stores_id'] = $list_v['stores_enter'];
                $goods_stocks = Db::name('kuyou_goods_stock')->where($where)->find();
                if(isset($goods_stock_add[$goods_stocks['id']])){
                    $goods_stock_add[$goods_stocks['id']]['stock'] += $stock_number;
                }else{
                    unset($goods_stocks['id']);
                    $goods_stocks['stock'] = $stock_number;
                    $goods_stocks['stores_id'] = $list_v['stores_out'];
                    $goods_stocks['createtime'] = time();
                    $goods_stocks['updatetime'] = time();
                    $goods_stock_add[$goods_stock['id']] = $goods_stocks;
                }
            }else{
                if(isset($goods_stock_edit[$goods_stock['id']])){
                    $goods_stock_edit[$goods_stock['id']] += $stock_number;
                }else{
                    $goods_stock_edit[$goods_stock['id']] = $goods_stock['stock']+$stock_number;
                }
            }
            foreach ($goods_stock_edit as $k=>$v){
                if($v<0){
                    return ['status'=>500,'msg'=>'商品'.$goods['goods_name'].'库存不足'];
                }
            }

            if($goods['batch']==1 && $batch==1){//启用批次管理
                $where = [];
                $where['goods_id'] = $goods['id'];
                if(!empty($list_v['goods_attr'])){
                    $where['attribute_id'] = $list_v['goods_attr'];
                }
                $where['stores_id'] = $list_v['stores_enter'];
                $where['batch_id'] = $list_v['goods_batch_id'];
                $goods_batch_stock = Db::name('kuyou_goods_batch_stock')->where($where)->find();
                if(empty($goods_batch_stock)){
                    return ['status'=>500,'msg'=>'商品'.$goods['goods_name'].'批次信息查询失败'];
                }else if($goods_batch_stock['stock']<$stock_number){
                    return ['status'=>500,'msg'=>'商品'.$goods['goods_name'].'批次'.$list_v['goods_batch_name'].'库存不足'];
                }else{
                    if(isset($goods_batch_edit[$goods_batch_stock['id']])){
                        $goods_batch_edit[$goods_batch_stock['id']] -= $stock_number;
                    }else{
                        $goods_batch_edit[$goods_batch_stock['id']] = $goods_batch_stock['stock']-$stock_number;
                    }
                }
                foreach ($goods_batch_edit as $k=>$v){
                    if($v<0){
                        return ['status'=>500,'msg'=>'商品'.$goods['goods_name'].'批次'.$list_v['goods_batch_name'].'库存不足'];
                    }
                }

                $where['stores_id'] = $list_v['stores_out'];
                $goods_batch_stock = Db::name('kuyou_goods_batch_stock')->where($where)->find();
                if(empty($goods_batch_stock)){//调出批次仓库无数据，新增仓储数据
                    $where['stores_id'] = $list_v['stores_enter'];
                    $goods_stocks = Db::name('kuyou_goods_batch_stock')->where($where)->find();
                    if(isset($goods_batch_add[$goods_stocks['id']])){
                        $goods_batch_add[$goods_stocks['id']]['stock'] += $stock_number;
                    }else{
                        unset($goods_stocks['id']);
                        $goods_stocks['stock'] = $stock_number;
                        $goods_stocks['stores_id'] = $list_v['stores_out'];
                        $goods_stocks['createtime'] = time();
                        $goods_stocks['updatetime'] = time();
                        $goods_batch_add[$goods_stock['id']] = $goods_stocks;
                    }
                }else{
                    if(isset($goods_batch_edit[$goods_batch_stock['id']])){
                        $goods_batch_edit[$goods_batch_stock['id']] += $stock_number;
                    }else{
                        $goods_batch_edit[$goods_batch_stock['id']] = $goods_batch_stock['stock']+$stock_number;
                    }
                }
            }
            if($goods['serial']==1 && $serial==1){//启用序列号管理
                if(empty($list_v['goods_serial_id'])){
                    return ['status'=>500,'msg'=>'请选择序列号'];
                }
                $goods_serial = unserialize($list_v['goods_serial_id']);
                $serial_number = [];
                foreach ($goods_serial as $goods_serial_k=>$goods_serial_v){
                    $serial_number[] = $goods_serial_v['serial'];
                }
                $where = [];
                $where['goods_id'] = $goods['id'];
                $where['attribute_id'] = $list_v['goods_attr'];
                $where['stores_id'] = $list_v['stores_enter'];
                $where['serial'] = ['in',$serial_number];
                $where['store_status'] = '1';
                $goods_number_stock = Db::name('kuyou_goods_serial')->where($where)->column('id');//需修改仓库的序列号ID
                if(sizeof($goods_number_stock)!=sizeof($serial_number)){
                    return ['status'=>500,'msg'=>'商品'.$goods['goods_name'].'序列号存在未在库，请重新选择'];
                }
                foreach ($goods_number_stock as $k=>$v){
                    if(!isset($serial_edit[$v])){
                        $serial_edit[$v] = ['id'=>$v,'stores_id'=>$list_v['stores_out']];
                    }
                }
            }
        }

        Db::startTrans();
        try {
            //收发详情
            if(!empty($info_ids)){
                Db::name('kuyou_goods_log')->where(['business_type'=>'6','purchase_id'=>['in',$info_ids]])->delete();
            }
            //删除批次跟踪
            if(!empty($info_ids)){
                Db::name('kuyou_goods_batch_log')->where(['business_type'=>'6','order_id'=>['in',$info_ids]])->delete();
            }

            $result = $model->where(['id'=>['in',$ids],'examine_status'=>'1'])
                ->update(['examine_status'=>'0','examine_id'=>'','examine_time'=>'','operation_id'=>$adminId]);
            if(!empty($goods_stock_add)){
                Db::name('kuyou_goods_stock')->insertAll($goods_stock_add);
            }
            if(!empty($goods_stock_edit)){
                foreach ($goods_stock_edit as $k=>$v){
                    Db::name('kuyou_goods_stock')->where(['id'=>$k])->update(['stock'=>$v]);
                }
            }
            if(!empty($goods_batch_add)){
                Db::name('kuyou_goods_batch_stock')->insertAll($goods_batch_add);
            }
            if(!empty($goods_batch_edit)){
                foreach ($goods_batch_edit as $k=>$v){
                    Db::name('kuyou_goods_batch_stock')->where(['id'=>$k])->update(['stock'=>$v]);
                }
            }
            if(!empty($serial_edit)){
                (new GoodsSerial())->saveAll($serial_edit);
            }
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            return ['status'=>500,'msg'=>$e->getMessage()];
        }
        if(isset($result) && $result !== false){
            return ['status'=>1,'msg'=>sizeof($list)];
        }else{
            return ['status'=>500,'msg'=>'反审核失败'];
        }
    }

}
